package com.liy.redisson.aop;
//

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
@Aspect  //表示该类是一个切面
@Component
public class LogAspect {

    /**
     * 日志记录器   this.getClass()放回当前运行时的对象
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 这个切面会横切com.liy.redisson包下控制器的请求
     */
    @Pointcut("execution(* com.liy.redisson.controller.*.*(..))")
    public void aspect(){

    }

    /**
     * 在切面前执行
     */
    @Before("aspect()")
    public void deBefore(JoinPoint joinPoint){
        logger.info("------------doBefore-----------");

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        //getDeclaringTypeName()获取目标方法所属类的类名，getName()获取目标方法
        //getArgs()获取传入目标方法的参数
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        logger.info("Result : {}",requestLog);
    }

    /**
     * 在切面方法后执行
     */
    @After("aspect()")
    public void doAfter(){
        logger.info("------------doAfter-----------");
    }
    /**
     * 该方法放回
     * @param result 放回的内容
     */
    @AfterReturning(returning = "result",pointcut = "aspect()")
    public void doAfterReturn(Object result){
        logger.info("Result : {}",result);
    }

    /**
     * 日志对象
     */
    private class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog(String url,String ip,String classMethod,Object[] args){
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{"+
                    "url='路径'" + url + '\''+
                    "，IP='"+ip + '\''+
                    "，classMethod='" + classMethod + '\'' +
                    "，args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
